from .basehandler import require_login, BaseHandler
from . import models
from andweb import utils
import hashlib

class DefaultHandler(BaseHandler):

	_template_dir = 'front'

	def oninit(self):
		super().oninit()
		title = utils.ordered_dict_getitem(self.config.topnav, self.page_name)
		if title:
			self.assign('title', title)

	def index(self):
		search = self.get_arg('search', None)
		articles = self.list_articles_desc('update_time')
		if search:
			articles = articles.filter(title__icontains=search)
		articles = articles[:10]
		return self.render(articles=articles)

	def hot(self):
		search = self.get_arg('search', None)
		articles = self.list_articles_desc('view_count')
		if search:
			articles = articles.filter(title__icontains=search)
		articles = articles[:10]
		return self.render(articles=articles)

	def type(self):
		data = self.get_args(('tag',))
		data.tags = (tag.name for tag in models.ArticleTag.objects.all())
		if data.tag:
			data.articles = self.list_articles_desc('create_time').filter(tags__icontains=data.tag)[:10]
		return self.render(**data)

	def login(self):
		if self.is_get:
			_next = self.get_arg('next', None)
			if _next == '':
				_next = self.referer
			if _next:
				self.session.setdefault('refer', _next)
			return self.render()
		else:
			data = self.get_args(('username', 'password'))
			origin_pwd = data.password
			self.sha1_pwd(data)
			user = models.User.objects.filter(**data).first()
			if not user:
				bind = models.Student.objects.filter(student_id=data.username, pwd=origin_pwd).first()
				if bind:
					data.role = models.User.STU
				else:
					bind = models.Teacher.objects.filter(teacher_id=data.username, pwd=origin_pwd).first()
					if bind:
						data.role = models.User.TEA
				if bind:
					data.nickname = bind.user_name
					user = models.User.objects.create(**data)
			if user:
				self.session['user'] = user.id
				return self.redirect(self.session.pop('refer', self.action('index')))
			else:
				return self.render(username=data.username, err='用户名或密码错误')

	def logout(self):
		self.session.pop('user', None)
		return self.redirect('login')

	def __register(self):
		if self.is_get:
			return self.render()
		else:
			data = self.get_args(('username', 'password', 'email'))
			if models.User.objects.filter(username=data.username).count():
				data.err='用户名已被注册'
			elif models.User.objects.filter(email=data.email).count():
				data.err='邮箱已被注册'
			if data.err:
				del data.password
				return self.render(**data)
			
			self.sha1_pwd(data)
			models.User.objects.create(**data)
			return self.redirect(self.action('login'))

	def list_articles_desc(self, order_by):
		return models.Article.find_public().order_by('-' + order_by)

	@staticmethod
	def sha1_pwd(data):
		data.password = hashlib.sha1(data.password.encode()).hexdigest()